let https = require('https');
const cheerio = require("cheerio");
const request = require("request");
const async = require("async");
let fs = require('fs');
let config = require("./config");

const http = require("http"); // 引入http核心模块
const server = http.createServer(); // createServer()方法返回一个server实例

let quest_id = config.quest_id;
let ans_sum = config.ans_sum;
let folder = config.folder;

let url =
  "https://www.zhihu.com/api/v4/questions/" + quest_id + "/answers?limit=20";
let ans_url = "https://www.zhihu.com/question/" + quest_id + "/answer/";

let answers = [];
let img_urls = [];

let option = config.option;

if (!fs.existsSync(folder)) {
    fs.mkdirSync(folder);
}

async.waterfall(
  [
    (cb_wf) => {
      let offset = 0;
      async.whilst(
        () => {
            // console.log('offset',offset );
            // console.log('ans_sum',ans_sum );
          return offset < ans_sum;
        },
        (cb_wh) => {
          let curr_url = url + "&offset=" + offset;
          option.url = curr_url;
          // console.log('option.url',option.url);
          request(option, (err, res, body) => {
            let result = JSON.parse(body);
            // console.log('result',result)
            // console.log('result',result);;
            ans_sum = result.paging.totals;
            result.data.forEach((ans,index) => {
              let st = ans.url.indexOf("/answers/");
              let ans_id = ans.url.substring(st + 9);
              answers.push(ans_id);
              console.log(((answers.length/ans_sum)*100).toFixed(1)+'%' ,'ansIdNumber:',answers.length+'/'+ans_sum);
            });
            // console.log('answers',answers);
            offset += 20;
            cb_wh();
          });
        },
        (err) => {
          if (err) {
            console.log(err);
            cb_wf(err);
          } else {
            console.log("Get answers finished.");
            cb_wf();
          }
        }
      );
    },
    (cb_wf) => {
      let curr_ans = 0;
      async.whilst(
        () => {
          return curr_ans+1 < answers.length;
        },
        (cb_wh) => {
          let curr_url = ans_url + answers[curr_ans++];
          option.url = curr_url;
          request(option, (err, res, body) => {
            if (err || res.statusCode != 200) {
              cb_wh(curr_url + " Error");
            } else {
              console.log('anUrl', curr_url, "finished");
              let $ = cheerio.load(body);

              // 定位答案页面html中的img，获取src
              let content = cheerio.load($(".RichContent-inner").html());
              content("img").each((i, elem) => {
                let img = content(elem).attr("src");
                if (img.indexOf("whitedot.jpg") == -1) {
                    if(img.substring(0,4)=='http')img_urls.push(img);
                }
              });
              const taskProgress = ((curr_ans/answers.length)*100).toFixed(1) + '%';
              console.log(taskProgress,'  loadsNumber:',curr_ans+'/'+answers.length);
              cb_wh();
            }
          });
        },
        (err) => {
          if (err) {
            console.log(err);
            cb_wf(err);
          } else {
            cb_wf();
          }
        }
      );
    },
  ],
  (err) => {
    if (err) {
      console.log(err);
    } else {
        // 本地服务启动
      server.on("request", (req, res) => {
        /*   给服务器绑定接收请求的处理事件，
          当服务器接收到客户端发送的请求后，
          会调用后面的处理函数，处理函数接收两个参数：
          请求信息对象，响应信息对象。 */
        const url = req.url;
        switch (url) {
          case "/":
            // 发送 HTTP 头部
            // HTTP 状态值: 200 : OK
            // 内容类型: text/plain
            let result={
                err:0,
                msg:'ok',
                status:200,
                data:img_urls,
                totals:img_urls.length
            }
            res.end(JSON.stringify(result));
            break;
          default:
            res.end("404 NOT FOUND");
            break;
        }
      });
      server.listen(8084, () => {
        //绑定监听端口号，开启服务器
        console.log("100%  服务器启动成功，访问 http://localhost:8084/ 获取数据");
        // server.listen()用来绑定监听的端口号，可以传入第二个参数，当服务器开启成功后，触发后面的回调函数
      });

    // 下载图片(放出注释即可使用)
    //   let img_cnt = 0;
    //   console.log("Total", img_urls.length, "imgs. Now downloading....");
    //   async.whilst(
    //       () => {
    //           return img_cnt < img_urls.length;
    //       },
    //       (cb) => {
    //           let html = "";
    //           https.get(img_urls[img_cnt++], (res) => {
    //               console.log('success');
    //               res.setEncoding('binary');
    //               res.on('data', (data) => {
    //                   html += data;
    //               });
    //               res.on('end', () => {
    //                   fs.writeFileSync(folder+ encodeURI(img_cnt) +'.jpg', html, 'binary');
    //                   console.log(img_cnt, "img finished");
    //                   cb();
    //               });
    //           });
    //       },
    //       (err) => {
    //           if (err) {
    //               console.log(err);
    //           } else {
    //               console.log("Img download finished");
    //           }
    //           process.exit();
    //       }
    //   );
    }
  }
);
